<template>
  <div class="short-user-page">
    <div class="container mx-auto px-4 py-8">
      <!-- 用户信息 -->
      <el-card class="user-card mb-6">
        <div class="user-header">
          <el-avatar :src="userInfo?.avatar" :size="100">
            {{ userInfo?.nickName?.charAt(0) || 'U' }}
          </el-avatar>
          <div class="user-details">
            <h1 class="text-2xl font-bold text-white">{{ userInfo?.nickName || '用户' }}</h1>
            <p class="text-gray-400 mt-2">{{ userInfo?.remark || '这个人很懒，什么都没留下' }}</p>
            <div class="stats mt-4">
              <div class="stat-item">
                <span class="stat-value">{{ formatCount(userStats?.shortsCount || 0) }}</span>
                <span class="stat-label">短视频</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ formatCount(userStats?.likesCount || 0) }}</span>
                <span class="stat-label">获赞</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ formatCount(userStats?.fansCount || 0) }}</span>
                <span class="stat-label">粉丝</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 短视频列表 -->
      <div class="shorts-grid">
        <h2 class="text-xl font-semibold text-white mb-4">
          TA的短视频 ({{ total }})
        </h2>

        <!-- 加载中 -->
        <div v-if="loading && shorts.length === 0" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          <el-skeleton v-for="i in 8" :key="i" animated>
            <template #template>
              <el-skeleton-item variant="image" style="width: 100%; height: 300px" />
            </template>
          </el-skeleton>
        </div>

        <!-- 短视频网格 -->
        <div v-else class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          <div
            v-for="short in shorts"
            :key="short.shortId"
            class="short-card"
            @click="navigateTo(`/shorts/${short.shortId}`)"
          >
            <div class="short-thumbnail">
              <el-image
                :src="short.poster"
                fit="cover"
                class="w-full h-full"
              >
                <template #error>
                  <div class="w-full h-full bg-gray-700 flex items-center justify-center">
                    <el-icon :size="40" color="#999">
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>

              <!-- 播放图标覆盖 -->
              <div class="play-overlay">
                <i class="i-carbon-play-filled text-4xl"></i>
              </div>

              <!-- 播放次数 -->
              <div class="view-count">
                <i class="i-carbon-view mr-1"></i>
                {{ formatCount(short.viewCount || 0) }}
              </div>
            </div>

            <div class="short-info">
              <p class="short-description">{{ short.description }}</p>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty v-if="!loading && shorts.length === 0" description="暂无短视频" />

        <!-- 加载更多 -->
        <div v-if="hasMore" ref="loadMoreRef" class="text-center py-8">
          <el-icon v-if="loadingMore" class="is-loading" :size="24">
            <Loading />
          </el-icon>
        </div>

        <!-- 已加载全部 -->
        <div v-if="!hasMore && shorts.length > 0" class="text-center py-4 text-gray-400">
          已加载全部短视频
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Loading, Picture } from '@element-plus/icons-vue'

const route = useRoute()
const userId = computed(() => route.params.id as string)

// 状态
const loading = ref(false)
const loadingMore = ref(false)
const userInfo = ref<any>(null)
const userStats = ref<any>(null)
const shorts = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)
const hasMore = ref(true)
const loadMoreRef = ref()

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await $fetch(`/dev-api/member/user/${userId.value}`)

    if (data.code === 200) {
      userInfo.value = data.data
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 模拟数据
    userInfo.value = {
      memberUserId: userId.value,
      nickName: '用户名',
      avatar: 'https://via.placeholder.com/100',
      remark: '这个人很懒，什么都没留下'
    }
  }
}

// 获取用户统计
const fetchUserStats = async () => {
  try {
    const data = await $fetch(`/dev-api/short/user/${userId.value}/stats`)

    if (data.code === 200) {
      userStats.value = data.data
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
    // 模拟数据
    userStats.value = {
      shortsCount: 42,
      likesCount: 1234,
      fansCount: 567
    }
  }
}

// 获取用户短视频列表
const fetchUserShorts = async (append = false) => {
  if (append) {
    loadingMore.value = true
  } else {
    loading.value = true
  }

  try {
    const data = await $fetch(`/dev-api/short/user/${userId.value}/list`, {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (data.code === 200) {
      const newShorts = data.rows || []

      if (append) {
        shorts.value = [...shorts.value, ...newShorts]
      } else {
        shorts.value = newShorts
      }

      total.value = data.total || 0
      hasMore.value = shorts.value.length < total.value
    }
  } catch (error) {
    console.error('获取用户短视频失败:', error)
    // 模拟数据
    const mockShorts = Array.from({ length: 12 }, (_, i) => ({
      shortId: i + 1,
      poster: `https://via.placeholder.com/300x400?text=Short${i + 1}`,
      description: `短视频描述 ${i + 1}`,
      viewCount: Math.floor(Math.random() * 10000),
      likes: Math.floor(Math.random() * 1000)
    }))

    if (append) {
      shorts.value = [...shorts.value, ...mockShorts]
    } else {
      shorts.value = mockShorts
    }

    total.value = 50
    hasMore.value = shorts.value.length < 50
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loadingMore.value) {
    currentPage.value++
    fetchUserShorts(true)
  }
}

// 格式化数字
const formatCount = (count: number) => {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + 'w'
  }
  if (count >= 1000) {
    return (count / 1000).toFixed(1) + 'k'
  }
  return count.toString()
}

// 监听滚动到底部
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      loadMore()
    }
  }, {
    threshold: 0.1
  })

  if (loadMoreRef.value) {
    observer.observe(loadMoreRef.value)
  }

  onUnmounted(() => {
    observer.disconnect()
  })
})

// 初始化
onMounted(async () => {
  await Promise.all([
    fetchUserInfo(),
    fetchUserStats(),
    fetchUserShorts()
  ])
})

// SEO
useSeoMeta({
  title: `${userInfo.value?.nickName || '用户'}的短视频`,
  description: userInfo.value?.remark || ''
})
</script>

<style scoped>
.short-user-page {
  min-height: 100vh;
  background-color: #0f0f0f;
  padding-top: 80px;
}

.user-card {
  background-color: rgba(31, 41, 55, 0.8);
  border: 1px solid rgba(55, 65, 81, 0.5);
}

.user-header {
  display: flex;
  gap: 24px;
  align-items: center;
}

@media (max-width: 768px) {
  .user-header {
    flex-direction: column;
    text-align: center;
  }
}

.user-details {
  flex: 1;
}

.stats {
  display: flex;
  gap: 32px;
}

@media (max-width: 768px) {
  .stats {
    justify-content: center;
  }
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #10b981;
}

.stat-label {
  font-size: 14px;
  color: #9ca3af;
  margin-top: 4px;
}

.shorts-grid {
  margin-top: 24px;
}

.short-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.short-card:hover {
  transform: translateY(-4px);
}

.short-thumbnail {
  position: relative;
  aspect-ratio: 9 / 16;
  border-radius: 8px;
  overflow: hidden;
  background-color: #1f2937;
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  color: white;
}

.short-card:hover .play-overlay {
  opacity: 1;
}

.view-count {
  position: absolute;
  bottom: 8px;
  left: 8px;
  display: flex;
  align-items: center;
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 4px;
  color: white;
  font-size: 12px;
  backdrop-filter: blur(4px);
}

.short-info {
  padding: 8px 0;
}

.short-description {
  color: #d1d5db;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
</style>
